package cn.echcz.restboot.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PathUtils {
    private PathUtils() {
        // util class
    }

    private static final Pattern pattern = Pattern.compile("/([^/]+)");
    private static final String[][] methodMappings = {{"GET", "R_R"}, {"HEAD", "R_H"}, {"OPTIONS", "R_O"},
            {"POST", "W_C"}, {"PUT", "W_U"}, {"DELETE", "W_D"}, {"PATCH", "W_P"}};


    /**
     * 将路径字符串转成列表，其中每一个元素表示一层路径
     * 主意: 只支持‘/’作为路径分隔符
     */
    public static List<String> pathStrToList(String pathStr) {
        List<String> result = new ArrayList<>();
        Matcher m = pattern.matcher(pathStr);
        while (m.find()) {
            result.add(m.group(1));
        }
        return result;
    }

    /**
     * 将http请求方法转化为路径操作方法
     */
    public static String httpMethodToPathMethod(String httpMethod) {
        for (String[] methodMapping : methodMappings) {
            if (methodMapping[0].equals(httpMethod)) {
                return methodMapping[1];
            }
        }
        return "R_R";
    }

    /**
     * 将路径操作方法转化为http请求方法
     */
    public static String pathMethodToHttpMethod(String pathMethod) {
        for (String[] methodMapping : methodMappings) {
            if (methodMapping[1].equals(pathMethod)) {
                return methodMapping[0];
            }
        }
        return "GET";
    }

}
